import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi } from '../api/auth'

interface UserInfo {
  id: number
  username: string
  permissions: string[]
}

export const useUserStore = defineStore('user', () => {
  const token = ref<string | null>(localStorage.getItem('token'))
  const userInfo = ref<UserInfo | null>(null)

  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
  }

  const hasPermission = (permission: string): boolean => {
    return userInfo.value?.permissions.includes(permission) || false
  }

  const login = async (username: string, password: string) => {
    try {
      const response = await loginApi(username, password)
      setToken(response.token)
      setUserInfo(response.userInfo)
      return true
    } catch (error) {
      return false
    }
  }

  const logout = () => {
    token.value = null
    userInfo.value = null
    localStorage.removeItem('token')
  }

  return {
    token,
    userInfo,
    login,
    logout,
    hasPermission
  }
}) 